<?php

namespace app\controller;

use app\BaseController;
use app\model\Activity;
use app\model\ActivityGoods;
use app\model\ActivityPromotionEffect;
use app\model\Category;
use app\model\Shop;
use app\traits\CommonTrait;
use app\traits\SyncGoodsEffectTrait;
use app\validate\ActivityStore;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;


class AdminActivity extends BaseController
{
    use CommonTrait;
    use SyncGoodsEffectTrait;

    //店铺识别
    public function shopTell()
    {
        $requestUrl = 'https://buyin.jinritemai.com/api/shop/list';
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/activity";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $shopIds = Request::get('shop_ids');
        if (!$shopIds) {
            return $this->apiJson(-1, '缺少店铺id参数');
        }
        $payload = ['shop_ids' => $shopIds];
        $client = new Client();
        try {
            $response = $client->request('GET', $requestUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['code'] == 0) {
            $shopData = $result['data'];
            $notExistNum = 0;
            foreach ($shopData as $v) {
                if ($v['exist'] == false) {
                    $notExistNum++;
                } else {
                    $shopExist = Shop::where(['shop_id' => $v['shop_id']])->findOrEmpty();
                    if ($shopExist->isEmpty()) {
                        Shop::create(['shop_id' => $v['shop_id'], 'shop_name' => $v['shop_name']]);
                    } else {
                        Shop::where(['shop_id' => $v['shop_id']])->update(['shop_name' => $v['shop_name']]);
                    }
                }
            }
            if ($notExistNum > 0) {
                return $this->apiJson(-1, $notExistNum . '个店铺ID无法识别，请删除后重新添加', $shopData);
            }
            return $this->apiJson(1, 'success', $result);
        } else {
            return $this->apiJson(-1, $result['msg']);
        }
    }

    // 发布 编辑活动
    public function save()
    {
        $byActivityId = Request::post('activity_id', 0);
        if ($byActivityId) {
            $activity = Activity::where(['buyin_activity_id' => $byActivityId])->field('id,buyin_activity_id,online')
                ->findOrEmpty();
            if ($activity->isEmpty()) {
                return $this->apiJson(-1, '活动不存在');
            }
            if (!$activity['buyin_activity_id'] || $activity['online'] == 1) {
                return $this->apiJson(-1, '该活动不满足修改条件');
            }
        }
        $payload = [
            /*活动类型 0专属招商 1公开招商;*/
            'activity_kind' => Request::post('activity_kind', 0),
            /* 招商方式 1全部商家 2指定商家*/
            'activity_type' => 1,
            /*指定的商家*/
            /*[{shop_id: "154417", shop_name: "味更佳食品饮料专营店"}]*/
            // 'specified_shop_ids' => Request::post('specified_shop_ids', ''),
            /*是否设置门槛 true false*/
            'threshold' => Request::post('threshold', false),
            /*店铺类型:0普通店 1专营店 2旗舰店 3专卖店 4商场店   [0,1,2,3,4]*/
            'shop_type' => Request::post('shop_type', [0, 1, 2, 3, 4]),
            'freshman_shop' => Request::post('freshman_shop', true),
            'is_new' => Request::post('is_new', true),
            /*商家体验分*/
            'shop_score' => Request::post('shop_score', 0),
            'activity_name' => Request::post('activity_name'),
            'activity_desc' => Request::post('activity_desc'),
            'apply_start_time' => Request::post('apply_start_time'),
            'apply_end_time' => Request::post('apply_end_time'),
            //  'apply_time'=>Request::post('apply_time'),
            //'apply_time'=>["2021-05-19T16:00:00.000Z","2021-05-19T16:00:00.000Z"],
            'promote_start_time' => Request::post('promote_start_time'),
            'promote_end_time' => Request::post('promote_end_time'),
            //  'promote_time'=>Request::post('promote_time'),
            'category' => Request::post('category'),
            'commission_rate' => Request::post('commission_rate'),
            'service_rate' => Request::post('service_rate'),
            'estimated_single_sale' => Request::post('estimated_single_sale'),
            'wechat_id' => Request::post('wechat_id', ''),
            'phone_num' => Request::post('phone_num', ''),
            'online' => Request::post('online', false)
        ];
        if ($byActivityId) {
            $payload['id'] = $byActivityId;
        }
        try {
            validate(ActivityStore::class)->check($payload);
        } catch (ValidateException $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/edit";
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/activity";

        try {
            // post form-data 请求
            $headers = [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
                'Referer' => $referUrl
            ];
            $cookies = config('app.buyin');
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('post', $url, ['form_params' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
            /*原始数据*/
//            $cookies = config('app.buyin');
//            $cookieStr = '';
//            foreach ($cookies as $k => $cookie) {
//                $cookieStr .= $k . '=' . $cookie.';';
//            }
//            $headers = [
//                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
//                'Referer' => $referUrl,
//                'Content-Type' => 'application/json',
//                'Cookie'=>$cookieStr
//            ];
//            //$payload = '{"activity_kind":0,"activity_type":1,"threshold":true,"shop_type":[0,1,2,3,4],"freshman_shop":true,"shop_score":0,"activity_name":"短视频种草2，10万达人带货【启】","activity_desc":"销量500+以上产品，评分4.6以上，义务供应链优先，佣金20+，请确保库存充足","apply_time":["2021-05-19T16:00:00.000Z","2021-05-19T16:00:00.000Z"],"promote_time":["2021-05-20T16:00:00.000Z","2021-05-20T16:00:00.000Z"],"commission_rate":"30","service_rate":"1","estimated_single_sale":"9.99","wechat_id":"18079160220","phone_num":"18079160220","is_new":true,"category":[18],"online":false,"id":"58913","promote_start_time":"2021-05-21","promote_end_time":"2021-05-21","apply_start_time":"2021-05-20","apply_end_time":"2021-05-20","specified_shop_ids":""}';
//            $response = $client->post($url, ['body' => json_encode($payload,JSON_UNESCAPED_UNICODE), 'debug'=>true,'headers' =>$headers]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            unset($payload['id']);
            $payload['apply_start_time'] = strtotime($payload['apply_start_time']);
            $payload['apply_end_time'] = strtotime($payload['apply_end_time']);
            $payload['promote_start_time'] = strtotime($payload['promote_start_time']);
            $payload['promote_end_time'] = strtotime($payload['promote_end_time']);
            $payload['category'] = json_encode($payload['category']);
            $payload['update_time'] = date('Y-m-d H:i:s', time());
            $payload['shop_type'] = json_encode($payload['shop_type']);
            if ($byActivityId) {
                Activity::where(['buyin_activity_id' => $byActivityId])->update($payload);
            } else {
                $payload['create_time'] = date('Y-m-d H:i:s', time());
                $insertId = Activity::insertGetId($payload);
                //更新巨量百应活动id
                $queryPayload = [
                    'status' => 0,
                    'page' => 1,
                    'activity_name' => Request::post('activity_name'),
                    'pageSize' => 20,
                    'page_size' => 20,
                ];
                $queryUrl = "https://buyin.jinritemai.com/api/institution/activity/list";
                try {
                    $queryResponse = $client->request('GET', $queryUrl, ['query' => $queryPayload, 'timeout' => 5, 'cookies' => $cookieJar]);
                } catch (\Exception $e) {
                    Log::info('活动查询失败:' . $e->getMessage());
                    return $this->apiJson(-1, '活动更新失败');
                }
                $queryResult = json_decode($queryResponse->getBody()->getContents(), true);
                if ($queryResult['code'] == 0) {
                    $activityList = $queryResult['data'];
                    if ($activityList) {
                        $buyinActivityId = $activityList[0]['id'];
                        Activity::where(['id' => $insertId])->update(['buyin_activity_id' => $buyinActivityId]);
                    } else {
                        return $this->apiJson(-1, '活动更新失败');
                    }
                } else {
                    return $this->apiJson(-1, '活动更新失败', $queryResult);
                }
            }
            return $this->apiJson(1, 'success', ['result' => $result]);
        } else {
            return $this->apiJson(-1, $result['msg'], $result);
        }
    }

    //活动列表
    public function myActivityList()
    {
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        //活动状态 1未上线 2报名未开始 3报名中 4 推广未开始 5推广中 6已结束
        $status = Request::get('status', 0);
        //活动名称
        $activityName = Request::get('activity_name', '');
//        $applyStartTime = Request::get('apply_start_time','');
//        $applyEndTime = Request::get('apply_end_time','');
        $where = [];
        if ($activityName) {
            $where[] = ['activity_name', 'like', "%$activityName%"];
        }
//        if(strtotime($applyStartTime)&&strtotime($applyEndTime)){
//            $where[] = ['apply_start_time','>=',strtotime($applyStartTime)];
//            $where[] = ['apply_end_time','<=',strtotime($applyEndTime)+86399];
//        }
        $where[] = ['is_del', '=', 0];
        switch ($status) {
            case 1:
                $where[] = ['online', '=', 0];
                break;
            case 2:
                $where[] = ['online', '=', 1];
                $where[] = ['apply_start_time', '>', time()];
                break;
            case 3:
                $where[] = ['online', '=', 1];
                $where[] = ['apply_start_time', '<=', time()];
                $where[] = ['apply_end_time', '>', time()];
                break;
            case 4:
                $where[] = ['online', '=', 1];
                $where[] = ['apply_end_time', '<', time()];
                $where[] = ['promote_start_time', '>', time()];
                break;
            case 5:
                $where[] = ['online', '=', 1];
                $where[] = ['apply_end_time', '<', time()];
                $where[] = ['promote_start_time', '<=', time()];
                $where[] = ['promote_end_time', '>', time()];
                break;
            case 6:
                $where[] = ['online', '=', 1];
                $where[] = ['promote_end_time', '<', time()];
                break;
            default:
                break;
        }
        $list = Activity::where($where)->field('id,buyin_activity_id,user_id,activity_name,activity_kind,apply_start_time,apply_end_time,
        promote_start_time,promote_end_time,commission_rate,service_rate,activity_desc,apply_num,un_audit_num,online')
            ->order('buyin_activity_id', 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $list);
    }

    /*活动详情*/
    public function activityDetail()
    {
        $activityId = Request::get('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $activityDetail = Activity::where(['buyin_activity_id' => $activityId, 'is_del' => 0])
            ->field('buyin_activity_id,activity_type,activity_name,activity_kind,apply_start_time,apply_end_time,promote_start_time,
            promote_end_time,commission_rate,service_rate,estimated_single_sale,category
            ,threshold,shop_type,is_new,shop_score,activity_desc,wechat_id,phone_num')
            ->findOrEmpty();
        if ($activityDetail->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        $detail = $activityDetail->toArray();
        if ($detail['category']) {
            $category = Category::whereIn('cid', $detail['category'])->where(['pid' => 0])->field('cid,cate_name')->select();
            $detail['category'] = $category;
        }
//        if ($detail['specified_shop_ids']) {
//            $specifiedShopInfos = Shop::whereIn('shop_id', $detail['specified_shop_ids'])->field('shop_id,name')->select();
//            $detail['specified_shop_infos'] = $specifiedShopInfos;
//        }
        return $this->apiJson(1, 'success', $detail);
    }

    //活动报名商品
    public function activityGoodsList()
    {
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $activityId = Request::get('activity_id');
        //商品名称或商品id
        $goodsInfo = Request::get('goods_info', '');
        //商家名称或商家id
        $shopInfo = Request::get('shop_info', '');
        $auditStatus = Request::get('audit_status', 0);
        $where = [];
        $where[] = ['audit_status', '=', $auditStatus];
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        if ($goodsInfo) {
            $where[] = ['product_name|product_id', 'like', "%$goodsInfo%"];
        }
        if ($shopInfo) {
            $where[] = ['shop_name|shop_id', 'like', "%$shopInfo%"];
        }
        $where[] = ['buyin_activity_id', '=', $activityId];
        $where[] = ['goods_type', '=', 1];
        $goodsList = ActivityGoods::where($where)
            ->field('id,apply_id,product_img,product_name,product_price,product_id,shop_name,shop_id,shop_phone,is_new,dsr,product_stock,
            common_commission_rate,commission_rate,service_rate,promotion_price,promotion_stock,gift_info,promotion_step,
            commission_effect_start_time,commission_effect_end_time,promotion_url')
            ->order('apply_id', 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $goodsList);
    }

    //推广收益
    public function promotionEffect()
    {
        $currentPage = Request::get('current_page', 1);
        $perPage = $this->getPerPage();
        $activityId = Request::get('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $productId = Request::get('product_id', '');
        $where = [];
        $where[] = ['buyin_activity_id', '=', $activityId];
        if ($productId) {
            $where[] = ['product_id', '=', $productId];
        }
        $list = ActivityPromotionEffect::where($where)
            ->field('product_id,product_name,product_img,product_price,commission_rate,service_rate,order_pay_num,order_pay_amount,estimated_service_fee')
            ->paginate(['list_rows' => $perPage, 'page' => $currentPage])->toArray();

        $sum = ActivityPromotionEffect::where($where)
            ->field('count(id) as promote_product_num,
            ifnull(sum(order_pay_num),0) as order_pay_num,
            ifnull(sum(order_pay_amount),0) as order_pay_amount,
            ifnull(sum(estimated_service_fee),0) as estimated_service_fee')
            ->select();
        $returnData = [
            'sum' => $sum[0],
            'list' => $list
        ];
        return $this->apiJson(1, 'success', $returnData);
    }

    //商品导出
    public function goodsExport()
    {
        $byActivityId = Request::param('activity_id');
        $auditStatus = Request::param('audit_status', 0);
        $startTime = Request::param('start_time') ? strtotime(Request::param('start_time')) : strtotime(date('Y-m-d', time()));
        $endTime = Request::param('end_time') ? strtotime(Request::param('end_time')) + 86399 : strtotime(date('Y-m-d', time())) + 86399;

        if (!$byActivityId) {
            return $this->apiJson(-1, '缺少buyin_activity_id参数');
        }
        $activity = Activity::where(['buyin_activity_id' => $byActivityId])
            ->field('buyin_activity_id,activity_name,online,apply_start_time,apply_end_time,
        promote_start_time,promote_end_time')->findOrEmpty();

        if ($activity->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        $activity = $activity->toArray();
        if ($activity['status'] == 3) {
            $applyUrl = 'https://buyin.jinritemai.com/dashboard/institution/activity-apply?id=' . $activity['buyin_activity_id'];
        } else {
            $applyUrl = '';
        }
        $where = [];
        $where[] = ['buyin_activity_id', '=', $byActivityId];
        $where[] = ['audit_status', '=', $auditStatus];
        $fileName = date('YmdHi', time()) . '.xlsx';
        $goodsList = ActivityGoods::where($where)
            ->whereTime('update_time', '>', $startTime)
            ->whereTime('update_time', '<=', $endTime)
            ->field('id,apply_id,product_img,product_name,product_price,product_id,shop_name,shop_id,shop_phone,is_new,dsr,product_stock,
            common_commission_rate,commission_rate,service_rate,promotion_price,promotion_stock,gift_info,promotion_step,
            commission_effect_start_time,commission_effect_end_time,promotion_url')
            ->select();
        $this->goodsToExcel($byActivityId, $activity['activity_name'], $applyUrl, $fileName, $goodsList);
    }

    public function goodsToExcel($byActivityId, $activityName, $applyUrl, $fileName, $goodsData)
    {
        if (!$goodsData) {
            return false;
        }
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->getStyle('A1:T1')->getFont()->getColor()->setARGB(Color::COLOR_RED);
        $objSheet->setTitle($byActivityId . '报名商品列表');  //设置当前sheet的标题
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('O')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('P')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('Q')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('R')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('S')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('T')->setAutoSize(true);

        $objSheet
            ->setCellValue('A1', '活动名称')
            ->setCellValue('B1', '报名链接')
            ->setCellValue('C1', '申请ID')
            ->setCellValue('D1', '商品名称')
            ->setCellValue('E1', '商品ID')
            ->setCellValue('F1', '商品售价')
            ->setCellValue('G1', '商家ID')
            ->setCellValue('H1', '商家名称')
            ->setCellValue('I1', '商家电话')
            ->setCellValue('J1', '店铺DSR')
            ->setCellValue('K1', '佣金生效开始时间')
            ->setCellValue('L1', '佣金生效截止时间')
            ->setCellValue('M1', '普通佣金率')
            ->setCellValue('N1', '团长佣金率')
            ->setCellValue('O1', '服务费率')
            ->setCellValue('P1', '活动价格')
            ->setCellValue('Q1', '活动库存')
            ->setCellValue('R1', '赠品信息')
            ->setCellValue('S1', '活动价实现方式')
            ->setCellValue('T1', '推广链接');
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        $count = count($goodsData);
        for ($i = 0; $i < $count; $i++) {
            $line = $i + 2;
            $objSheet->setCellValue('A' . $line, $activityName)
                ->setCellValue('B' . $line, $applyUrl)
                ->setCellValue('C' . $line, $goodsData[$i]['apply_id'])
                ->setCellValue('D' . $line, $goodsData[$i]['product_name'])
                ->setCellValue('E' . $line, " " . $goodsData[$i]['product_id'])
                ->setCellValue('F' . $line, round($goodsData[$i]['product_price'] / 100, 2))
                ->setCellValue('G' . $line, $goodsData[$i]['shop_id'])
                ->setCellValue('H' . $line, $goodsData[$i]['shop_name'])
                ->setCellValue('I' . $line, $goodsData[$i]['shop_phone'])
                ->setCellValue('J' . $line, $goodsData[$i]['dsr'])
                ->setCellValue('K' . $line, $goodsData[$i]['commission_effect_start_time'])
                ->setCellValue('L' . $line, $goodsData[$i]['commission_effect_end_time'])
                ->setCellValue('M' . $line, $goodsData[$i]['common_commission_rate'])
                ->setCellValue('N' . $line, $goodsData[$i]['commission_rate'])
                ->setCellValue('O' . $line, $goodsData[$i]['service_rate'])
                ->setCellValue('P' . $line, $goodsData[$i]['promotion_price'])
                ->setCellValue('Q' . $line, $goodsData[$i]['promotion_stock'])
                ->setCellValue('R' . $line, $goodsData[$i]['gift_info'])
                ->setCellValue('S' . $line, $goodsData[$i]['promotion_step'])
                ->setCellValue('T' . $line, $goodsData[$i]['promotion_url']);
        }
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition: attachment;filename=" . $fileName);
        header('Cache-Control: max-age=1');
        header('Pragma: public');
        $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
        $objWriter->save('php://output');
    }

    //活动操作 上线online 下线offline 删除delete
    public function activityOperation()
    {
        $activityId = Request::post('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $activityExist = Activity::where(['buyin_activity_id' => $activityId, 'is_del' => 0])->field('id')->findOrEmpty();
        if ($activityExist->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        $operation = Request::post('operation');
        if (!in_array($operation, ['online', 'offline', 'delete'])) {
            return $this->apiJson(-1, '非法操作');
        }
        $payload = [
            'activity_id' => $activityId,
            'operation' => $operation,
        ];
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/operation";
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('post', $url, ['form_params' => $payload, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            switch ($operation) {
                case 'online':
                    Activity::where(['buyin_activity_id' => $activityId])->update(['online' => 1]);
                    break;
                case 'offline':
                    Activity::where(['buyin_activity_id' => $activityId])->update(['online' => 0]);
                    break;
                case 'delete':
                    Activity::where(['buyin_activity_id' => $activityId])->update(['is_del' => 1]);
                    break;
            }
            return $this->apiJson(1, 'success');
        } else {
            return $this->apiJson(-1, $result['msg']);
        }
    }

    //活动商品 审核拒绝
    public function activityAuditOperation()
    {
        $applyId = Request::post('apply_id');
        if (!$applyId) {
            return $this->apiJson(-1, '缺少apply_id参数');
        }
        $applyExist = ActivityGoods::where(['apply_id' => $applyId, 'goods_type' => 1])->field('id')->findOrEmpty();
        if ($applyExist->isEmpty()) {
            return $this->apiJson(-1, '报名不存在');
        }
        $operation = Request::post('operation');
        if (!in_array($operation, ['pass', 'reject'])) {
            return $this->apiJson(-1, '非法操作');
        }
        $payload = [
            'apply_id' => $applyId,
            'operation' => $operation
        ];
        // 是否可重复报名
        $repeatApply = Request::post('repeat_apply', 1);
        $suggestInfo = Request::post('suggest_info', '');
        if ($operation == 'reject') {
            $auditStatus = 2;
            $payload['repeat_apply'] = $repeatApply;
            $payload['suggest_info'] = $suggestInfo;
        } else {
            $auditStatus = 1;
        }
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/operation";
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('post', $url, ['form_params' => $payload, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            ActivityGoods::where(['apply_id' => $applyId])->update(['audit_status' => $auditStatus]);
            return $this->apiJson(1, 'success');
        } else {
            return $this->apiJson(-1, $result['msg']);
        }
    }

    // 刷新报名商品
    public function refreshApplyGoods()
    {
        $activityId = Request::post('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $activityExist = Activity::where(['buyin_activity_id' => $activityId, 'is_del' => 0])->findOrEmpty();
        if ($activityExist->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        for ($i = 0; $i <= 2; $i++) {
            $page = 1;
            $finish = false;
            $url = "https://buyin.jinritemai.com/api/institution/activity/audit/list";
            $cookies = config('app.buyin');
            $client = new Client();
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            do {
                $payload = [
                    'audit_status' => $i,
                    'activity_id' => $activityId,
                    'page' => $page,
                    'pageSize' => 50,
                    'page_size' => 50,
                ];
                try {
                    $response = $client->request('GET', $url, ['query' => $payload, 'timeout' => 5, 'cookies' => $cookieJar]);
                } catch (\Exception $e) {
                    Log::info('调用接口失败' . $e->getMessage());
                    return $this->apiJson(-1, '接口调用失败');
                }
                $result = json_decode($response->getBody()->getContents(), true);
                if (!$result) {
                    return $this->apiJson(-9, '巨浪百应账号登录已过期');
                }
                if ($result['code'] == 0) {
                    $goodsList = $result['data'];
                    if ($goodsList) {
                        foreach ($goodsList as $v) {
                            $goodsExist = Db::name('activity_goods')->where(['apply_id' => $v['apply_id']])
                                ->field('id')->find();
                            if ($goodsExist) {
                                $goods = [
                                    'product_id' => $v['product_id'],
                                    'product_promotion_id' => $v['product_promotion_id'],
                                    'product_name' => $v['product_name'],
                                    'product_price' => $v['product_price'],
                                    'product_img' => $v['product_img'],
                                    'product_stock' => $v['product_stock'],
                                    'shop_name' => $v['shop_name'],
                                    'shop_id' => $v['shop_id'],
                                    'dsr' => $v['dsr'],
                                    'shop_phone' => $v['shop_phone'],
                                    'is_new' => $v['is_new'] ? 1 : 0,
                                    'commission_effect_start_time' => $v['commission_effect_start_time'],
                                    'commission_effect_end_time' => $v['commission_effect_end_time'],
                                    'commission_rate' => $v['commission_rate'],
                                    'common_commission_rate' => $v['common_commission_rate'],
                                    'service_rate' => $v['service_rate'],
                                    'promotion_url' => $v['promotion_url'],
                                    'promotion_price' => $v['promotion_price'],
                                    'promotion_stock' => $v['promotion_stock'],
                                    'gift_info' => $v['gift_info'],
                                    'promotion_step' => $v['promotion_step'],
                                    'audit_status' => $i,
                                    'commission' => round(($v['commission_rate'] * $v['promotion_price']) / 100, 2),
                                    'update_time' => date('Y-m-d H:i:s', time())
                                ];
                                Db::name('activity_goods')->where(['apply_id' => $v['apply_id']])->update($goods);
                            } else {
                                $goods = [
                                    'buyin_activity_id' => $activityId,
                                    'apply_id' => $v['apply_id'],
                                    'product_id' => $v['product_id'],
                                    'product_promotion_id' => $v['product_promotion_id'],
                                    'product_name' => $v['product_name'],
                                    'product_price' => $v['product_price'],
                                    'product_img' => $v['product_img'],
                                    'product_stock' => $v['product_stock'],
                                    'shop_name' => $v['shop_name'],
                                    'shop_id' => $v['shop_id'],
                                    'dsr' => $v['dsr'],
                                    'shop_phone' => $v['shop_phone'],
                                    'is_new' => $v['is_new'] ? 1 : 0,
                                    'commission_effect_start_time' => $v['commission_effect_start_time'],
                                    'commission_effect_end_time' => $v['commission_effect_end_time'],
                                    'commission_rate' => $v['commission_rate'],
                                    'common_commission_rate' => $v['common_commission_rate'],
                                    'service_rate' => $v['service_rate'],
                                    'promotion_url' => $v['promotion_url'],
                                    'promotion_price' => $v['promotion_price'],
                                    'promotion_stock' => $v['promotion_stock'],
                                    'gift_info' => $v['gift_info'],
                                    'promotion_step' => $v['promotion_step'],
                                    'audit_status' => $i,
                                    'commission' => round(($v['commission_rate'] * $v['promotion_price']) / 100, 2),
                                    'create_time' => date('Y-m-d H:i:s', time()),
                                    'update_time' => date('Y-m-d H:i:s', time())
                                ];
                                Db::name('activity_goods')->insert($goods);
                            }
                        }
                    }
                } else {
                    Log::info('活动同步失败:' . $result['msg']);
                    return $this->apiJson(-1, '接口调用失败');
                }
                $totalPage = ceil($result['total'] / 50);
                $page++;
                // 当前页数 > 总页数
                if ($page > $totalPage) {
                    $finish = true;
                }
            } while (!$finish);
        }
        return $this->apiJson(1, 'success');
    }

    //刷新推广效果
    public function refreshPromotionEffect()
    {
        $activityId = Request::post('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $activityExist = Activity::where(['buyin_activity_id' => $activityId, 'is_del' => 0])->field('id')->findOrEmpty();
        if ($activityExist->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        $result = $this->getPromotionEffect($activityId);
        if ($result['code'] != 1) {
            return $this->apiJson($result['code'], $result['msg']);
        }
        /*$result['data']*/
        return $this->apiJson(1, 'success');
    }

    //刷新服务费列表
    public function refreshServiceFeeList()
    {
        $productId = Request::post('product_id');
        if (!$productId) {
            return $this->apiJson(-1, '缺少product_id参数');
        }
        $activityExist = ActivityGoods::where(['product_id' => $productId])->field('id')->findOrEmpty();
        if ($activityExist->isEmpty()) {
            return $this->apiJson(-1, '活动不存在');
        }
        $result = $this->getServiceFeeList($productId);
        if ($result['code'] != 1) {
            return $this->apiJson($result['code'], $result['msg']);
        }
        return $this->apiJson(1, 'success');
    }

    /* 实时接口 */

    //实时 招商活动列表
    public function realTimeActivityList()
    {
        $currentPage = Request::get('current_page', 1);
        $perPage = $this->getPerPage();
        /* 0全部 1未上线 2报名未开始 3报名中 4 推广未开始 5推广中 6已结束*/
        $status = Request::get('status', 0);
        $activityName = Request::get('activity_name', '');
        $payload = [
            'status' => $status,
            'page' => $currentPage,
            'pageSize' => $perPage,
            'page_size' => $perPage,
        ];
        if ($activityName != '') {
            $payload['activity_name'] = $activityName;
        }
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/list";
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/activity";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('GET', $url, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            return $this->apiJson(1, 'success', $result);
        } else {
            return $this->apiJson(-1, $result['msg']);
        }
    }

    //实时 报名商品列表
    public function realTimeActivityGoodsList()
    {
        $currentPage = Request::get('current_page', 1);
        $perPage = $this->getPerPage();
        $auditStatus = Request::get('audit_status', 0);
        $activityId = Request::get('activity_id');
        //商品名称或商品id
        $productInfo = Request::get('product_info', '');
        //商家名称或商家id
        $shopInfo = Request::get('shop_info', '');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少活动id');
        }
        $referUrl = 'https://buyin.jinritemai.com/dashboard/institution/goods?id=' . $activityId;
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $payload = [
            'audit_status' => $auditStatus,
            'activity_id' => $activityId,
            'page' => $currentPage,
            'pageSize' => $perPage,
            'page_size' => $perPage,
        ];
        if ($productInfo != '') {
            $payload['product_info'] = $productInfo;
        }
        if ($shopInfo != '') {
            $payload['shop_info'] = $shopInfo;
        }
        $client = new Client();
        $url = "https://buyin.jinritemai.com/api/institution/activity/audit/list";
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('GET', $url, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            return $this->apiJson(1, 'success', $result);
        } else {
            return $this->apiJson(-1, $result['msg']);
        }
    }

    //活动实时推广效果
    public function realTimePromotionEffect()
    {
        $currentPage = Request::get('current_page', 1);
        $perPage = $this->getPerPage();
        $activityId = Request::get('activity_id');
        if (!$activityId) {
            return $this->apiJson(-1, '缺少activity_id参数');
        }
        $productId = Request::get('product_id', '');
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/goods?id=" . $activityId;
        $requestUrl = "https://buyin.jinritemai.com/api/common/promotion/effect";
        $payload = [
            'activity_id' => $activityId,
            'page' => $currentPage,
            'pageSize' => $perPage,
            'page_size' => $perPage
        ];
        if ($productId != '') {
            $payload['product_id'] = $productId;
        }
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $client = new Client();
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            // debug 'debug'=>true
            $response = $client->request('GET', $requestUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            return $this->apiJson(1, 'success', $result);
        } else {
            return $this->apiJson($result['code'], $result['msg']);
        }
    }

    //活动实时服务费明细
    public function realTimeServiceFeeList()
    {
        $currentPage = Request::get('current_page', 1);
        $perPage = $this->getPerPage();
        $productId = Request::get('product_id');
        if (!$productId) {
            return $this->apiJson(-1, '缺少product_id参数');
        }
        // 0 全部 1已付款 2已退款 3已结算
        $orderStatus = Request::get('order_status', 0);
        if (!in_array($orderStatus, [0, 1, 2, 3])) {
            $orderStatus = 0;
        }
        $searchType = Request::get('search_type', 'pay');
        if ($searchType != 'pay' && $searchType != 'settle') {
            return $this->apiJson(-1, '时间筛选条件不对');
        }
        $orderId = Request::get('order_id', '');
        $startTime = Request::get('start_time', Carbon::now()->toDateTimeString());
        $endTime = Request::get('end_time', Carbon::now()->subDays(7)->toDateTimeString());
        $startDate = Carbon::parse($startTime);
        $endDate = Carbon::parse($endTime);
        $dateDiff = $startDate->diffInDays($endDate);
        if ($dateDiff > 90) {
            return $this->apiJson(-1, '日期范围最多支持90天,请缩短查询时间范围', $dateDiff);
        }
        $payload = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'order_status' => $orderStatus,
            'product_id' => $productId,
            'search_type' => $searchType,
            'page' => $currentPage,
            'pageSize' => $perPage,
            'page_size' => $perPage
        ];
        if ($orderId) {
            $payload['order_id'] = $orderId;
        }
        $referUrl = "https://buyin.jinritemai.com/dashboard/institution/serviceCharge?productId=" . $productId;
        $requestUrl = "https://buyin.jinritemai.com/api/common/service/fee/list";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $client = new Client();
        $cookies = config('app.buyin');
        try {
            $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
            $response = $client->request('GET', $requestUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if (!$result) {
            return $this->apiJson(-9, '巨浪百应账号登录已过期');
        }
        if ($result['code'] == 0) {
            return $this->apiJson(1, 'success', $result);
        } else {
            return $this->apiJson($result['code'], $result['msg']);
        }
    }
}
